# auth/serializers.py
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from .models import SessionLog, FamilyMember

# serializers.py
from rest_framework import serializers
from .models import Family, InvitationCode

class FamilySerializer(serializers.ModelSerializer):
    class Meta:
        model = Family
        fields = ['id', 'name', 'manager']
        extra_kwargs = {
            'manager': {'read_only': True}
        }

class InvitationCodeSerializer(serializers.ModelSerializer):
    class Meta:
        model = InvitationCode
        fields = ['code', 'expires_at']
        extra_kwargs = {
            'expires_at': {'read_only':True, 'required': False}
        }

class JoinFamilySerializer(serializers.Serializer):
    code = serializers.CharField(max_length=36)


class FamilyMemberSerializer(serializers.ModelSerializer):
    # 显示关联的用户名和家庭名称
    username = serializers.CharField(source='user.username')
    family_name = serializers.CharField(source='family.name')
    role = serializers.CharField(source='get_role_display')  # 显示中文角色

    class Meta:
        model = FamilyMember
        fields = ['id', 'username', 'family_name', 'role', 'joined_at']
        read_only_fields = ['joined_at']


class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        data = super().validate(attrs)

        # 创建会话记录
        session = SessionLog.objects.create(
            user=self.user,
            ip=self.context['request'].META.get('REMOTE_ADDR'),
            user_agent=self.context['request'].META.get('HTTP_USER_AGENT', '')[:150]
        )

        # 在 Token 中嵌入 session_id
        refresh = self.get_token(self.user)
        refresh['session_id'] = session.id  # 关键：存储会话ID

        data['refresh'] = str(refresh)
        data['access'] = str(refresh.access_token)

        return data